package com.ys.controller.api.storage;

import com.ys.config.MenuId;
import com.ys.entity.amazonorder.TpAmazonShopOrderDaily;
import com.ys.entity.storage.TccOfflineAssembleItem;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.storage.TccOfflineAssembleService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/tccOfflineAssemble")
public class ApiInterTccOfflineAssembleController {
	
	private static final Logger logger = Logger.getLogger(ApiInterTccOfflineAssembleController.class);
	
	@Autowired
	private TccOfflineAssembleService tccOfflineAssembleService;
	
	@Autowired
	private CommonApiService<TccOfflineAssembleItem> commonApiService;

	@RequiresPermissions("tccOfflineAssemble:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TccOfflineAssembleItem cond, String conditions){
		cond.setStatus(1);//数据过滤
		String _ys_createTime = ConditionUtil.getConditionValue(conditions, "_ys_createTime");//创建时间
		if (_ys_createTime != null && _ys_createTime.length() > 0) {
			String[] timeDays = _ys_createTime.split(" ~ ");
			cond.where("ola.CreateTime >= '" + timeDays[0] + "' and ola.CreateTime <= '" + timeDays[1] + "'");
		}
		String _ys_auditTime = ConditionUtil.getConditionValue(conditions, "_ys_auditTime");//组装时间
		if (_ys_auditTime != null && _ys_auditTime.length() > 0) {
			String[] timeDays = _ys_auditTime.split(" ~ ");
			cond.where("ola.auditTime >= '" + timeDays[0] + "' and ola.auditTime <= '" + timeDays[1] + "'");
		}
		String _ys_state = ConditionUtil.getConditionValue(conditions, "_ys_state");//组装状态
		if (_ys_state != null){
			if (!_ys_state.equals("3")){
				cond.where("ola.state = " + _ys_state);
			}
		}else {
			cond.where("ola.state = 0");
		}
        cond = setSeachSql(cond,conditions);

		//权限
		cond = commonApiService.dataAuth(MenuId.TCC_OfflineAssemble, cond);
		LayuiTableVoJA vo = commonApiService.searchLay(cond);
		return vo;
	}

    /**
     * 设置查询的cond的sql设置
     */
    private TccOfflineAssembleItem setSeachSql(TccOfflineAssembleItem cond, String conditions){

        cond.addLeftJoin("TCC_OfflineAssemble ola ON ola.Bid = A.Pbid")
        .addField("ola.Bid bid")//入库单号
        .addField("ola.id offlineAssembleId")//组装id
        .addField("ola.printStatus printStatus")//打印状态
        .addField("ola.ParentAssembleNumber parentAssembleNumber")//实际组装数量
        .addField("ola.ParentPreAssembleNumber parentPreAssembleNumber")//采购数量
        .addField("ola.AuditTime auditTime")//审核时间
        .addField("ola.auditingUserId auditingUserId")//审核工号
        .addField("ola.State state")//组装状态
        .addField("ola.CreateTime _ys_createTime")//创建时间
        .addField("ola.auditTime _ys_auditTime")//组装时间
        .addField("ola.assemblyListBid")//组长清单号
		.addLeftJoin("TS_UserChange B on B.UserId = ola.auditingUserId AND B.status = 1")
		.addField("B.UserName auditingUserName")//运营人
		.addLeftJoin("TCG_OfflinePurchaseInStorage opi on opi.id = A.offlinePurchaseStorageId")
		.addField("opi.productCode")//商品编码
		.addField("opi.productName")//商品名称
		.addField("opi.productImgOne")//商品图片1
		.addField("opi.productImgTwo")//商品图片2
		.addField("opi.productImgThree")//商品图片3
		.addField("opi.bid offlinePurchaseInStorageBid")//采购入库单号
		.addField("opi.subCode")//子件编码
		.addField("opi.subName")//子件名称
		.addField("opi.subBomNumber")//子件BOM数量
		.addField("opi.subPurchasePrice")//子件采购单价
		.addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = opi.Vgsbm ")//运营公司管理表
		.addField("E.Vgsjc AS vgsjc")//采购公司简称
		.addField("E.vgsbm AS vgsbm")//采购公司编码
		.addLeftJoin("TS_UserChange BU on BU.Id = E.OperatorChangeId")
		.addField("BU.UserId operatorUserId")//运营人工号
		.addField("BU.UserName operatorUserName")//运营人
		.addLeftJoin("TCG_PurchaseByOrderSon C ON C.id = opi.PurchaseOrderSonId")
		.addLeftJoin("TCG_PurchaseByOrder AA ON C.Pid = AA.id")
		.addField("AA.AliOrderNumber AS aliOrderNumber,AA.Bid purchaseOrderBid,AA.id purchaseOrderId")//1688订单编号
		.addLeftJoin("TCG_PurchaseByPlan H ON H.Bid = AA.PlanBid")//采购计划表
		.addField("H.bid AS purchasePlanBid")//计划单号
		.addLeftJoin("TCC_Location CC ON CC.Chw = opi.Chw")
		.addLeftJoin("TCC_WarehouseArea CWA ON CWA.Ckq = CC.Ckq")//库区
		.addLeftJoin("TCC_Warehouse CW ON CW.Cck = CWA.Cck")//仓库
		.addField("CW.vck,CWA.vkq,CC.vhw")
		.addField("A.subPlanStorageNum - A.subRealStorageNum - A.subAssembleLeftNum AS subAssembleLostNum")//子件组装缺失数量
        ;
        return  cond;
    }
	
	/**
	 * 正常组装
	 */
	@RequiresPermissions("tccOfflineAssemble:batchPass")
	@PostMapping("/batchPass")
    @ResponseBody
	public R batchPass(String bids) {

		logger.info("批量通过正常组装bids---" + bids);
		if (bids == null || bids.length() == 0) {
			return R.error("单号有误");
		}
		try {
			return tccOfflineAssembleService.pass(bids);
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		}
	}

	/**
	 * 异常组装
	 */
	@RequiresPermissions("tccOfflineAssemble:exception")
	@PostMapping("/doError")
    @ResponseBody
	public R doError(HttpServletRequest request,
			String bid, Integer parentAssembleNumber, String subData) throws Exception{
		
		logger.info("bid---" + bid);
		logger.info("subData---" + subData);
		
		try {
			return tccOfflineAssembleService.doError(bid, parentAssembleNumber, subData);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("数据出错，请联系客服处理");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("tccOfflineAssemble:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TccOfflineAssembleItem cond, String conditions) throws Exception{
		cond.setStatus(1);//数据过滤
		String _ys_createTime = ConditionUtil.getConditionValue(conditions, "_ys_createTime");//创建时间
		if (_ys_createTime != null && _ys_createTime.length() > 0) {
			String[] timeDays = _ys_createTime.split(" ~ ");
			cond.where("ola.CreateTime >= '" + timeDays[0] + "' and ola.CreateTime <= '" + timeDays[1] + "'");
		}
		String _ys_auditTime = ConditionUtil.getConditionValue(conditions, "_ys_auditTime");//组装时间
		if (_ys_auditTime != null && _ys_auditTime.length() > 0) {
			String[] timeDays = _ys_auditTime.split(" ~ ");
			cond.where("ola.auditTime >= '" + timeDays[0] + "' and ola.auditTime <= '" + timeDays[1] + "'");
		}
		cond = setSeachSql(cond,conditions);

		//权限
		cond = commonApiService.dataAuth(MenuId.TCC_OfflineAssemble, cond);
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCC_OfflineAssemble)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
    	
        ExportExcelUtils<TccOfflineAssembleItem> util = new ExportExcelUtils<TccOfflineAssembleItem>(new TccOfflineAssembleItem());
        
        String toFilePath = util.exportExcel(listData, listField, "线上商品组装单");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

	/**
	 * 组装清单打印
	 */
	@RequiresPermissions("tccOfflineAssemble:printing")
	@PostMapping("/printing")
	@ResponseBody
	public R printing(String bids) {

		logger.info("批量通过组装清单打印bids---" + bids);
		if (bids == null || bids.length() == 0) {
			return R.error("单号有误");
		}
		try {
			return tccOfflineAssembleService.printing(bids);
		} catch (Exception e) {
			logger.error("组装清单打印出错：",e.getMessage(),e);
			return R.error("打印失败!");
		}
	}

	/**
	 * 入库箱标打印
	 */
	@RequiresPermissions("tccOfflineAssemble:dy")
	@RequestMapping("/getPdf")
	@ResponseBody
	public R getPdf(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			//入库箱标打印
			return tccOfflineAssembleService.getPdf(params);
		} catch (Exception e) {
			logger.error("入库箱标打印出错：",e.getMessage(),e);
			return R.error("打印失败!");
		}
	}

	/**
	 * 入库箱标打印
	 */
	@RequestMapping("/getPdfZj")
	@ResponseBody
	public R getPdfZj(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			//入库箱标打印
			return tccOfflineAssembleService.getPdfZj(params);
		} catch (Exception e) {
			logger.error("入库箱标打印出错：",e.getMessage(),e);
			return R.error("打印失败!");
		}
	}

	/**
	 * 取消组装
	 */
	@RequiresPermissions("tccOfflineAssemble:cancel")
	@PostMapping("/cancel")
	@ResponseBody
	public R cancel(HttpServletRequest request,
					 String bid) throws Exception{
		logger.info("bid---" + bid);
		try {
			return tccOfflineAssembleService.cancel(bid);
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		}
	}
}
